package hikari.persistence.handlersimpl;

import com.gooddies.wiring.Wiring;
import com.gooddies.wiring.annotations.Wire;
import com.gooddies.wiring.annotations.WiringComponent;
import hikari.gui.assets.AssetsTree;
import hikari.gui.panels.ScriptPanel;
import hikari.objects3d.Basic3dObject;
import hikari.persistence.file.Chunk;
import hikari.persistence.file.FileSection;
import hikari.persistence.persisthandlers.IPersistantObject3dReadHandler;
import hikari.persistence.persisthandlers.PersistantHandler;
import hikari.script.propertyeditors.FloatPropertyEditor;
import hikari.script.propertyeditors.IntegerPropertyEditor;
import hikari.utils.Utils;
import java.io.IOException;
import java.util.List;
import org.swig.jirr.ISceneManager;

/**
 * @author sad
 */
@WiringComponent(singleton = true, lazy = true)
@PersistantHandler(sectionName = "script")
public class ScriptLoadHandler implements IPersistantObject3dReadHandler {

    @Wire
    private AssetsTree assetsTree;
    @Wire
    private Utils utils;

    private ScriptLoadHandler() {
    }

    @Override
    public Basic3dObject read(ISceneManager sceneManager, Basic3dObject object, FileSection section) throws IOException {
        ScriptPanel script = Wiring.getComponent(ScriptPanel.class);
        String path = section.readString(section.getChunk("path"));
        String absolutePath = assetsTree.getAbsoluteAssetPathFromRelativePath(path);
        script.setScriptPath(absolutePath);
        if (section.getChunk("name") != null) {
            String name = section.readString(section.getChunk("name"));
            script.setHComponentName(name);
        }
        if (section.getChunk("enabled") != null) {
            boolean enabled = section.readBoolean(section.getChunk("enabled"));
            script.setHComponentEnabled(enabled);
        }
        List<Chunk> props = section.getAllSections();
        for (Chunk chunk : props) {
            switch (chunk.getName()) {
                case "int": {
                    IntegerPropertyEditor editor = new IntegerPropertyEditor("", 0);
                    editor.load(section.readSection(chunk));
                    break;
                }
                case "float": {
                    FloatPropertyEditor editor = new FloatPropertyEditor("", 0);
                    editor.load(section.readSection(chunk));
                    break;
                }
                default: {
                    utils.logError("Cannot find editor for property " + chunk.getName());
                    return null;
                }
            }
        }
        object.addHComponent(script);
        return object;
    }
}
